package hspcn

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/cookiejar"
	"strconv"
	"time"
)

type HspSite struct {
	RootURL   string
	HspCookie []*http.Cookie
}

func NewHspSite() *HspSite {
	instance := new(HspSite)
	instance.RootURL = "https://www.hspcn.com/"
	return instance
}

// 获得验证码等信息
func (c *HspSite) GetVirificationCode() ([]byte, error) {

	rnd := strconv.FormatInt(time.Now().UnixNano(), 10)
	path := "/home/index/getCaptchaPic?t=" + rnd
	url := c.RootURL + path

	var jar *cookiejar.Jar
	jar, _ = cookiejar.New(nil)
	httpClient := &http.Client{
		Jar: jar,
	}

	// 设置 cookie
	var httpReq *http.Request
	httpReq, _ = http.NewRequest("GET", url, nil)
	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		log.Println(err.Error())
		return nil, err
	}
	defer httpResp.Body.Close()

	if httpResp.StatusCode != 200 {
		err = fmt.Errorf("StatusCode:%d Status:%s", httpResp.StatusCode, httpResp.Status)
		return nil, err
	}

	c.HspCookie = jar.Cookies(httpReq.URL)
	return ioutil.ReadAll(httpResp.Body)
}
